// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let res = await db.collection('UserRelationship')
    .aggregate()
    .match({
      inviter: wxContext.OPENID,
    })
    .lookup({
      from: 'User',
      localField: 'invitee',
      foreignField: '_openid',
      as: 'user',
    })
    .end()
  let res2 = await db.collection('UserRelationship')
    .aggregate()
    .match({
      invitee: wxContext.OPENID,
    })
    .lookup({
      from: 'User',
      localField: 'inviter',
      foreignField: '_openid',
      as: 'user',
    })
    .end()

  let friends = []
  if (res.list.length > 0) {
    for (let i = 0; i < res.list.length; i++) {
      let user1 = res.list[i].user[0]
      user1.relationship = "我邀请的"
      friends.push(user1)
    }
  }
  if (res2.list.length > 0) {
    for (let j = 0; j < res2.list.length; j++) {
      let user2 = res2.list[j].user[0]
      user2.relationship = "邀请我的"
      friends.push(user2)
    }
  }
  return friends

}